package main

import (
	"encoding/json"
	"gitee.com/Cookie_XiaoD/go-filestore-server/config"
	"gitee.com/Cookie_XiaoD/go-filestore-server/db"
	"gitee.com/Cookie_XiaoD/go-filestore-server/mq"
	"gitee.com/Cookie_XiaoD/go-filestore-server/store/alioss"
	"log"
	"os"
	"time"
)

func main() {
	if !config.RabbitMQCfg.EnableAsyncTransfer {
		log.Println("目前异步转移功能已被禁用")
		return
	}
	log.Println("启动文件异步转移服务")
	for {
		err := mq.StartConsumer(config.RabbitMQCfg.TransOSSQueueName, "oss_transfer", handleMsg)
		if err == mq.DisConnectError {
			log.Println("5秒后尝试重新消费")
			time.Sleep(5 * time.Second)
			continue
		}
		break
	}
	log.Println("文件异步转移服务结束")
}

func handleMsg(msg []byte) bool {
	if len(msg) == 0 {
		return true
	}
	msgInfo := string(msg)
	log.Printf("接收到消息：%v", msgInfo)
	//1.解析消息
	msgData := &mq.TransferData{}
	if err := json.Unmarshal(msg, msgData); err != nil {
		//无效消息直接丢弃
		log.Printf("反序列化失败 错误：%v", err.Error())
		return true
	}
	//2.根据文件当前本地路径获取文件句柄
	file, err := os.Open(msgData.CurLocation)
	if err != nil {
		log.Printf("打开文件失败,路径：%v 错误：%v", msgData.CurLocation, err.Error())
		return false
	}
	defer file.Close()

	//3.将文件保存到OSS
	if err := alioss.GetBucket().PutObject(msgData.DestLocation, file); err != nil {
		log.Printf("保存文件到OSS失败,路径：%v 错误：%v", msgData.DestLocation, err.Error())
		return false
	}

	//4.更新文件元信息，将Location更新为OSS地址
	if err := db.UpdateFileLocation(msgData.FileHash, msgData.DestLocation); err != nil {
		log.Printf("更新文件路径异常，文件哈希：%v 错误:%v", msgData.FileHash, err.Error())
		return false
	}

	return true
}
